<template>
  <div class="text">
    <div class="tleft">
      <div class="lup" >
        <img src="../assets/dlogo.png" alt="" class="lup1">
        <div class="lup2 noselect xiaoshou">大模型</div>
      </div>
      <div class="lmiddle">
        <img src="../assets/ava.png" alt="" class="lmd1">
        <div class="lmd2 noselect">Moon</div>
      </div>
      <div class="ldown" >
        <div :class="selectNum==index?'ldownlist center lightbluecss wightFontcss':'ldownlist center'" 
             v-for="(item,index) in list" 
             :key="index" 
             @click="selectTap(index)">
          <div class="ldownlist1 center">
            <img class="ldownlist11 noselect xiaoshou" :src="item.icon" alt="">
          </div>
          <div class="ldownlist2 noselect xiaoshou">{{ item.name }}</div>
        </div>
        
        <!-- 历史会话列表 -->
        <div v-if="selectNum === 1" class="history-list">
          <div v-for="(session, idx) in historyList" 
               :key="idx" 
               class="history-item"
               @click="loadHistorySession(session.session_id)">
            <div class="history-title">{{ session.title }}</div>
            <div class="history-time">{{ session.last_time }}</div>
          </div>
          <div v-if="historyList.length === 0" class="no-history">
            暂无历史会话
          </div>
        </div>
      </div>
    </div>
    <div class="tright">
      <div class="rup">
        <div class="rup3"></div>
        <div class="rup0">
        <img src="../assets/tou.png" alt="" class="rup1">
    <el-dropdown >
    <span class="el-dropdown-link noselect">
      Qin
      <img src="../assets/arrow.png" alt="" class="rup2">
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item>个人信息</el-dropdown-item>
        <el-dropdown-item>系统设置</el-dropdown-item>
        <el-dropdown-item>联系我们</el-dropdown-item>
        <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
    </div>
  </div>
      <div class="rdown">
        <div class="rdmid">
          <div class="rdm1 noselect" v-if="sendStatus==0">早上好</div>

          <div class="rdm0" ref="messageContainer" v-if="sendStatus==1">
            <div :class="index%2==0?'usercss':'botcss'" v-for="(item,index) in list1" :key="index">
              <div class="rdm01"></div>
              <div :class="index%2==0?'rdm010 ':'rdm011 '">
                <img v-if="index%2!==0" src="../assets/ava.png" class="rdm012">
                {{ item.content }}</div>
            </div>
          </div>

          <div class="rdm2" v-if="sendStatus==0">
            <textarea name="" id="" class="rdm21" placeholder="请输入内容" @keyup.enter="sendMsg" v-model="textarea2"></textarea>
            <div class="rdm22">
              <div class="rdm221 noselect xiaoshou">
                <img src="../assets/think.png" alt="" class="rdm2211">
                <div class="rdm2212">深度思考</div>
              </div>
              <div class="rdm224"></div>
              <div class="rdm222 noselect xiaoshou">
              <img src="../assets/link.png" alt="" class="rdm2221">
              </div>
              <div class="rdm223 noselect xiaoshou"  @click="sendMsg">
                <img src="../assets/uparrow.png" alt="" class="rdm2231">
              </div>

            </div>
          </div>
          <div class="rdm20" v-if="sendStatus==1">
            <textarea name="" id="" class="rdm21" placeholder="请输入内容" @keyup.enter="sendMsg" v-model="textarea2"></textarea>
            <div class="rdm22">
              <div class="rdm221 noselect xiaoshou" @focus="get" @blur="out">
                <img src="../assets/think.png" alt="" class="rdm2211">
                <div class="rdm2212">深度思考</div>
              </div>
              <div class="rdm224"></div>
              <div class="rdm222 noselect xiaoshou">
              <img src="../assets/link.png" alt="" class="rdm2221">
              </div>
              <div class="rdm223 noselect xiaoshou"  @click="sendMsg" >
                <img src="../assets/uparrow1.png" alt="" class="rdm22310">
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const selectNum = ref(0)
const sendStatus = ref(0)
const list1 = ref([])
const textarea2 = ref('')
const messageContainer = ref(null)
const sessionId = ref(null)
const isLoading = ref(false)
const historyList = ref([]) // 存储历史会话列表

// 获取用户信息
const userInfo = ref(JSON.parse(sessionStorage.getItem('userInfo')) || {
  id: null,
  email: '',
  username: ''
})

const list = ref([
  { name: '新建会话', icon: require('../assets/chat.png') },
  { name: '历史会话', icon: require('../assets/hchat.png') },
  { name: 'Ai搜索', icon: require('../assets/serch.png') },
  { name: 'Ai编程', icon: require('../assets/pro.png') },
])

// 修改后的 selectTap 函数
const selectTap = (index) => {
  selectNum.value = index
  if (index === 0) {
    // 新建会话
    list1.value = []
    sendStatus.value = 0
    sessionId.value = null
  } else if (index === 1) {
    // 加载历史会话列表
    loadHistoryList()
  }
}

// 加载历史会话列表
const loadHistoryList = async () => {
  try {
    if (!userInfo.value.id) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('http://localhost:9000/api/chats', {
      params: {
        userId: userInfo.value.id
      }
    })
    
    if (response.data.code === 200) {
      historyList.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '加载历史会话失败')
    }
  } catch (error) {
    console.error('加载历史会话列表失败:', error)
    ElMessage.error('加载历史会话列表失败')
  }
}

// 加载特定会话的历史记录
const loadHistorySession = async (sessionIdToLoad) => {
  try {
    const response = await axios.get('http://localhost:9000/api/chat/history', {
      params: {
        sessionId: sessionIdToLoad
      }
    })
    
    if (response.data.code === 200) {
      list1.value = response.data.data.map(msg => ({
        role: msg.role,
        content: msg.content
      }))
      sessionId.value = sessionIdToLoad
      sendStatus.value = 1
      nextTick(() => {
        scrollToBottom()
      })
    } else {
      ElMessage.error(response.data.msg || '加载历史记录失败')
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
    ElMessage.error('加载历史记录失败')
  }
}

const sendMsg = async () => {
  const content = textarea2.value.trim()
  if (!content) {
    ElMessage.warning('请输入内容')
    return
  }

  if (isLoading.value) return
  isLoading.value = true
  sendStatus.value = 1

  try {
    list1.value.push({ role: 'user', content })
    textarea2.value = ''
    scrollToBottom()

    const response = await axios.post('http://localhost:9000/api/chat', {
      content,
      user: userInfo.value,
      sessionId: sessionId.value
    })
    
    const data = response.data
    if (data.code === 200) {
      list1.value.push({ 
        role: 'bot', 
        content: data.data.content 
      })
      
      // 更新会话ID
      if (!sessionId.value) {
        sessionId.value = data.data.sessionId
      }
    } else {
      ElMessage.error(data.msg || '获取回答失败')
    }
  } catch (error) {
    console.error('请求大模型失败:', error)
    ElMessage.error('网络错误，请稍后再试')
    list1.value.push({ 
      role: 'bot', 
      content: '抱歉，获取回答时出错，请稍后再试' 
    })
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

const logout = () => {
  router.push('/LonginViews')
}

onMounted(() => {
  if (list1.value.length > 0 && messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
})
</script>

<style scoped>
/* 样式保持不变 */
.text{
  display: flex;
  border-radius: 10px;
  height: 96vh;
  width: 99vw;
  background-color:white ;
  overflow: hidden;
}
.tleft{
display: flex;
flex-direction:column;
 justify-content: flex-start; 
height: 100%;
width: 260px;
background-color:rgb(2, 2, 72) ;
}
.tright{
  flex:1;
display: flex;
flex-direction:column;
}
.lup{
  display: flex; 
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100%;
}
.lup1{
  width: 40px;
}
.lup2{
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin-left: 10px;
}
.lmiddle{
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 160px;
  width: 100%;
}
.lmd1{
  width: 80px;
  border-radius:100px ;
  margin-left: 30px;
  margin-bottom: 5px;
  transition: 0.2s;
}
.lmd1:hover{
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.872);
}
.lmd2{
  color: aliceblue;
  font-size: 24px;
  font-weight: 600;
  margin-left: 30px;
}

.ldown{
  flex: 1;
  position: relative;
}
.ldownlist11{
  width: 30px;
  padding-right: 10px;
}
.ldownlist2{
  color: white;
}
.ldownlist{
  display: flex;
  align-items: center;
  justify-content: center;
  width: 250px;
  height: 70px;
  border-radius: 20px;
  transition:transform 0.2s ;
}

.ldownlist:hover{
  background-color: #7b8d9f;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(65, 65, 65, 0.788);
}
.ldownlist:active{
  transform: scale(0.97) translateY(-1px);
}

/* 新增历史会话列表样式 */
.history-list {
  position: absolute;
  top: 280px;
  left: 0;
  width: 100%;
  max-height: calc(100% - 280px);
  overflow-y: auto;
  background-color: rgba(2, 2, 72, 0.95);
  border-top: 1px solid #555;
  padding: 10px 0;
  z-index: 10;
}

.history-item {
  padding: 12px 20px;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:hover {
  background-color: rgba(123, 141, 159, 0.5);
}

.history-title {
  font-size: 16px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-time {
  font-size: 12px;
  color: #aaa;
  margin-top: 4px;
}

.no-history {
  padding: 20px;
  text-align: center;
  color: #aaa;
  font-size: 14px;
}

.rup{
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  background-color: rgb(237, 237, 236);
}
.rup3{
  width: 2px;
  height: 100%;
  background-color: white;
}
.rup0{
flex: 1;
  margin-right: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.rup1{
  width: 50px;
  border-radius: 100%;
  margin-right: 10px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.el-dropdown-link{
  border: none;
  outline: none;
}
.el-dropdown-link:hover,.rup1:hover{
  transform: translateY(-0.5px);
  box-shadow: 0 4px 6px -1px rgba(89, 89, 89, 0.788);
}
.rup2{
  width: 15px;
  vertical-align: middle;
}

.rdown{
  flex: 1;
  display: flex;
  justify-content: center;
}
.rdmid{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; 
  width: 850px;
  min-height: 100%; /* 替代 height: 100% */
  height: auto;    
}
.rdm1{
  font-size: 36px;
  font-weight: 500;
}
.rdm0{
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}
.usercss{
  background-color: #dedfe0;
  margin-bottom: 10px;
  border-radius: 10px;
  padding: 5px 10px;
  max-width: 50%; /* 最大宽度不超过容器 */
  width: fit-content; /* 宽度根据内容自适应 */
  word-wrap: break-word; /* 允许长单词换行 */
  white-space: normal; /* 正常换行行为 */
  overflow-wrap: break-word; /* 在需要时打断单词 */
  border: 1px solid #ccc; /* 基础边框 */
  margin-left: auto; /* 新增：使元素靠右 */
  margin-right: 20px; /* 新增：右侧间距20px */
  margin-top: 25px;
}
.rdm011{
  display: flex;
}
.botcss{
  display: flex;
  align-items: center;
}
.rdm012{
  width: 30px;
  height: 30px;
  border-radius: 100%;
  display: flex;
  align-items: center;
  padding-right: 5px;
}
.rdm2{
  width: 800px;
  height: 150px;
  margin-top: 10px;
  border-radius: 15px;
  border: 2px solid rgb(235, 234, 234);
  display: flex;
  flex-direction: column;
}
.rdm20{
  width: 800px;
  height: 150px;
  padding-top: 10px;
  margin-top: auto;
  margin-bottom: 20px;
  border-radius: 15px;
  border: 2px solid rgb(235, 234, 234);
  display: flex;
  flex-direction: column;
}
.rdm21{
  height: 50%;
  width: 770px;
  margin: 10px 10px 0px 10px;
  border: none;
  outline: none;
  resize: none; /* 可选：禁止调整大小 */
}
.rdm22{
  flex: 1;
  display: flex;
  align-items: center;
}
.rdm221{
  width: 100px;
  height: 35px;
  background-color: rgb(235, 236, 237);
  border: 2px solid rgb(220, 219, 219);
  border-radius: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 20px;
}

.rdm2211{
  width: 20px;
  margin-right: 5px;
}
.rdm222{
  width: 30px;
  height:30px;
  background-color: rgb(235, 236, 237);
  border: 2px solid rgb(220, 219, 219);
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}
.rdm2221{
  width: 20px;
}

.rdm2231{
  width: 40px;
  margin-right: 20px;
}
.rdm22310{
  width: 40px;
  margin-right: 20px;
}
.rdm22310:active{
  transform: scale(0.98);
}
.rdm221:hover,.rdm222:hover{
  transform: translateY(-1px);
  border-color: cornflowerblue;
  background-color: rgb(234, 244, 244);
}
.rdm221:active,.rdm222:active{
  transform: scale(0.98);
  background-color: rgb(157, 188, 244);;
}
.rdm224{
  flex: 1;
}
</style>